package com.s59.rbac.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.s59.rbac.redis.RedisUtils;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;

@Aspect
@Component
public class RequiredPermsAspect {
    @Autowired
    private RedisUtils redisUtils;

    @Around(value = "@annotation(com.s59.rbac.common.RequiredPerms)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        RequiredPerms annotation = method.getDeclaredAnnotation(RequiredPerms.class);
        if (checkPerms(annotation.value())){
            return joinPoint.proceed();
        }
        throw new AccessDeniedException("无权访问");
    }

    @SneakyThrows
    private boolean checkPerms(String value) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        String token = servletRequestAttributes.getRequest().getHeader("token");
        String json = redisUtils.get(Constants.CACHE_PREFIX_TOKEN + token);
        if (StringUtils.hasText(json)){
            LoginUser loginUser = new ObjectMapper().readValue(json, LoginUser.class);
            return loginUser.getPermsList().contains(value);
        }
        return false;
    }

}
